package com.nwpu.hass.utils.faceutils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * http 工具类
 */
@Slf4j
public class HttpUtil {

    private static String wechat_appID = "wx4569cc8135067949";

    private static String wechat_appSecret = "784316c06c216be400d1249ac2387256";


    public static String post(String requestUrl, String accessToken, String params)
            throws Exception {
        String contentType = "application/x-www-form-urlencoded";
        return HttpUtil.post(requestUrl, accessToken, contentType, params);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params)
            throws Exception {
        String encoding = "UTF-8";
        if (requestUrl.contains("nlp")) {
            encoding = "GBK";
        }
        return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
    }

    public static String getOpenId(String requestUrl, String code)
            throws Exception {

        String url = requestUrl + "?" + "appid=" + wechat_appID
                + "&secret=" + wechat_appSecret
                +"&js_code=" + code
                + "&grant_type=authorization_code";
        log.info("请求OpenId的URL： " + url);
        String encoding = "UTF-8";
        String contentType = "application/json";

        return HttpUtil.getGeneralUrl(url, contentType, encoding);
    }
    public static String getAccessToken() throws Exception {

        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + wechat_appID +
                "&secret=" + wechat_appSecret;
        log.info("请求AccessToken的URL： " + url);

        String encoding = "UTF-8";
        String contentType = "application/json";
        return HttpUtil.getGeneralUrl(url, contentType, encoding);
    }

    public static void main(String[] args) throws Exception {
        System.out.println(HttpUtil.getAccessToken());
    }
    public static Boolean sendSubscribe(String accessToken,String open_id,String deviceId){

        String temp_id = "wwChG5Um9dRgLVWbn3_gAYSXFi-_6DqxOw9-8retKbE";
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?" +
                "access_token=" +
                accessToken;
        Date now = new Date();
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String today = f.format(now);

        String encoding = "UTF-8";
        String contentType = "application/json";

        //32位以内数字、字母或符号
        String key1 = "character_string1";
        String v1 = deviceId;

        //5个以内汉字
        String key2 = "phrase4";
        String v2 = "设备损坏";

        //年月日格式（支持+24小时制时间），支持填时间段，两个时间点之间用“~”符号连接
        String key3 = "date3";
        String v3 = today;

        //10个以内纯汉字或20个以内纯字母或符号
        String key4 = "name2";
        String v4 = "HASS";

        String params = "{\n" +
                "  \"touser\": \"" + open_id + "\",\n" +
                "  \"template_id\": \"" + temp_id + "\",\n" +
                "  \"page\": \"index\",\n" +
                "  \"miniprogram_state\":\"developer\",\n" +
                "  \"lang\":\"zh_CN\",\n" +
                "  \"data\": {\n" +
                "      \"" + key1 + "\": {\n" +
                "          \"value\": \"" + v1 + "\"\n" +
                "      },\n" +
                "      \"" + key2 + "\": {\n" +
                "          \"value\": \"" + v2 + "\"\n" +
                "      },\n" +
                "      \"" + key3 + "\": {\n" +
                "          \"value\": \"" + v3 + "\"\n" +
                "      } ,\n" +
                "      \"" + key4 + "\": {\n" +
                "          \"value\": \"" + v4 +"\"\n" +
                "      }\n" +
                "  }\n" +
                "}\n" +
                "\n";

        try {
            String res = HttpUtil.postGeneralUrl(url, contentType,params, encoding);
            log.info(res);
        }catch (Exception e){
            return false;
        }
        return true;

    }


    public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
            throws Exception {
        String url = requestUrl + "?access_token=" + accessToken;
        return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
    }

    public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
            throws Exception {
        URL url = new URL(generalUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        if(params != null){
            out.write(params.getBytes(encoding));
        }
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> headers = connection.getHeaderFields();
        // 遍历所有的响应头字段
        for (String key : headers.keySet()) {
            log.info(key + "--->" + headers.get(key));
        }
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), encoding));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        return result;
    }
    public static String getGeneralUrl(String generalUrl, String contentType, String encoding)
            throws Exception {
        URL url = new URL(generalUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> headers = connection.getHeaderFields();
        // 遍历所有的响应头字段
        for (String key : headers.keySet()) {
            log.error(key + "--->" + headers.get(key));
        }
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), encoding));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        return result;
    }
}
